/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package me.yobol.algorithm.basic.math;

import java.util.Scanner;

/**
 *
 * @author Yobol
 */
public class Factorial {
    
    /**
     * 以递归方式求第n个斐波那契数
     * 
     * @param n
     * @return
     * @throws IllegalStateException 
     */
    public static long factorialByRecursion(int n) throws IllegalStateException{
        if (n < 0) {
            throw new IllegalStateException("n不能小于0！");
        }
        
        if(n == 0 || n == 1){
            return 1;
        }else{
            return n * factorialByRecursion(n - 1);
        }
    }
    
    /**
     * 以for循环方式求第n个斐波那契数
     * 
     * @param n
     * @return
     * @throws IllegalStateException 
     */
    public static long factorialByForCirculation(int n) throws IllegalStateException{
        int result = 1;
        if (n < 0) {
            throw new IllegalStateException("n不能小于0！");
        }
        
        if (n == 0) {
            return result;
        }
        
        for(int i = 1;i <= n;i++){
            result *= i;
        }
        
        return result;
    }
    
    public static void main(String[] args) {
        int n = -1;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个大于0的整数：");
        n = scanner.nextInt();
        System.out.println(n);
        System.out.println("递归方式：" + factorialByRecursion(n));
        System.out.println("for循环" + factorialByForCirculation(n));
    }
}
